import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import mimetypes
import pytest
import time

class SendingEmails:
    def __init__(self, from_addr, to_addr, smtp_server, smtp_port, password):
        """
        初始化发件人、收件人、SMTP服务器和端口以及密码。

        这些属性用于配置电子邮件的发送参数。

        参数:
        from_addr: 发件人邮箱地址。
        to_addr: 收件人邮箱地址。
        smtp_server: SMTP服务器地址。
        smtp_port: SMTP服务器端口。
        password: 发件人邮箱的授权密码。
        """
        self.from_addr = from_addr
        self.to_addr = to_addr
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.password = password


    def send_html_email(self, subject, content):
        """
        发送HTML格式的电子邮件。

        使用SMTP_SSL建立安全连接，登录邮箱，然后发送邮件。如果发送成功，打印成功消息；如果发送失败，打印失败原因。

        参数:
        subject - 邮件主题。
        content - 邮件正文，以HTML格式提供。
        """
        # 创建MIMEText对象，设置内容类型为HTML，编码为UTF-8
        msg = MIMEText(content, 'html', 'utf-8')

        # 设置邮件的发件人、收件人和主题
        msg['From'] = Header(self.from_addr)
        msg['To'] = Header(self.to_addr)
        msg['Subject'] = Header(subject)

        try:
            # 初始化SMTP_SSL客户端，指定邮箱服务器和端口
            smtp_server = smtplib.SMTP_SSL(self.smtp_server, self.smtp_port)
            # 登录邮箱
            smtp_server.login(self.from_addr, self.password)
            # 发送邮件
            smtp_server.sendmail(self.from_addr, self.to_addr, msg.as_string())
            # 关闭SMTP连接
            smtp_server.quit()
            # 邮件发送成功，打印提示信息
            print('邮件发送成功')
        except smtplib.SMTPException as e:
            # 邮件发送失败，打印失败信息和异常详情
            print('邮件发送失败', e)


# 可以添加附件
def send_email(from_addr, password, to_addr, subject, content,attachment_files=[]):
    msg = MIMEMultipart()
    msg['From'] = Header(from_addr)
    msg['To'] = Header(to_addr)
    msg['Subject'] = Header(subject, 'utf-8')
    # 添加正⽂内容
    msg.attach(MIMEText(content, 'plain'))
    try:
        for file in attachment_files:
            content_type, encoding = mimetypes.guess_type(file) # 获取⽂件类型
            if content_type is None or encoding is not None:
                content_type = 'application/octet-stream' # 默认使⽤application/octet-stream
            with open(file, 'rb') as f:
                part = MIMEBase(*content_type.split('/'))
                part.set_payload(f.read())
                encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment', filename=file)
            msg.attach(part)

            # 发送邮件
            smtp_server = 'smtp.qq.com'
            smtpobj= smtplib.SMTP_SSL(smtp_server, 465)
            smtpobj.login(from_addr, password)
            smtpobj.sendmail(from_addr, to_addr, msg.as_string())
            print("邮件发送成功")
    except Exception as e:
        print("⽆法发送邮件:", e)
    finally:
        smtpobj.quit()

import os
import zipfile # python自带
# 打包测试报告
def dfs_get_zip_file(input_path, result):
    files = os.listdir(input_path)
    for file in files:
        if os.path.isdir(input_path + '/' + file):
            dfs_get_zip_file(input_path + '/' + file, result)  # 是目录递归
        else:
            result.append(input_path + '/' + file)  # 是文件拼接路径并添加

def zip_path(input_path, output_path, output_name):

    f = zipfile.ZipFile(output_path + '/' + output_name, 'w', zipfile.ZIP_DEFLATED)
    filelists = []
    dfs_get_zip_file(input_path, filelists)
    for file in filelists:
        f.write(file)
    f.close()
    return output_path + r"/" + output_name


if __name__ == '__main__':
    # 发信方邮箱和授权码
    from_addr = '1799250443@qq.com'
    password = 'nbukekpuuhhsbagb'
    # 收信方邮箱
    to_addr = '1799250443@qq.com'
    # 发信服务器
    smtp_server = 'smtp.qq.com'
    port = 465
    subject='主题就是主题'
    html_msg = """
    <p>你好这是一个测试邮件，请查收：主题就是主题</p>
    <a href='https://www.runoob.com/'>菜鸟教程</a>
    """
    # send_email = SendingEmails(from_addr, to_addr, smtp_server, port, password)
    # send_email.send_html_email(subject, html_msg)

    #---------------
    # pytest.main(["-v", "--html=./report/测试报告.html",'test_calc.py'])
    # time.sleep(10)

    # 使用示例
    report_folder = r'./report'  # 测试报告文件夹路径
    output_folder = r'./zip'  # 输出的ZIP文件名
    output_name='test_report.zip'
    # zip_path(report_folder,output_folder,output_name)

    attachment_files = [f'{output_folder}/{output_name}']  # 附件⽂件列表
    send_email(from_addr, password, to_addr, subject, html_msg, attachment_files)
